package com.caseProject.puremvc.mediator.view
{
	import com.caseProject.puremvc.mediator.gui.Graphic;
	import com.caseProject.puremvc.mediator.gui.GraphicFormat;
	
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Rectangle;
	
	public class StageView extends Sprite
	{
		private var container:Sprite;
		
		public function StageView()
		{
			super();
			
			this.container = new Sprite();	
			this.addEventListener(Event.ADDED_TO_STAGE, onInit);
		}
		
		protected function onInit(event:Event):void
		{
			this.stage.addEventListener (Event.RESIZE, onResize);
					
			this.container.addEventListener(Event.ADDED_TO_STAGE, onInitContainer);
			this.addChild(this.container);
		}
		
		private function drawBackgroud ():void
		{
			var gf:GraphicFormat = new GraphicFormat ();
			gf.fillColor = 0xEAEAEA;
			var g:Graphics = gf.doFormat(this.container);
			var w:Number = this.stage.stageWidth - this.x - 5;
			var h:Number = this.stage.stageHeight - this.y - 5;
						
			g.drawRect(0, 0, w, h);
			
			this.scrollRect = new Rectangle(0,0,width,height);			
		}
		
		public function clearStage():void
		{
			if (this.container != null && this.contains(this.container))
			{
				this.removeChild(this.container);
				this.container = new Sprite();		
				this.container.addEventListener(Event.ADDED_TO_STAGE, onInitContainer);		
				this.addChild(this.container);
				this.drawBackgroud();
			}
		}
		
		protected function onInitContainer(event:Event):void
		{
			this.drawBackgroud ();
		}
				
		protected function onResize(event:Event):void
		{
			if (this.stage != null)
			{				
				this.drawBackgroud ();
			}
		}
		
		/**
		 * Add Graphic to StageView
		 * */
		public function addElement(e:Graphic):void
		{
			this.container.addChild(e);
		}
		
		public function getElementAt(index:int):Graphic
		{
			return this.container.getChildAt(index) as Graphic;
		}
		
		public function get numElements():int
		{
			return this.container.numChildren;
		}
		
		public function removeElement (e:Graphic):void
		{
			this.container.removeChild(e);
		}
		
		public function removeGraphics(vo:Object):void
		{
			var length:int = this.container.numChildren;
			for (var i:int = 0; i < length; i++)
			{
				if (this.container.getChildAt(i)["vo"] == vo)
				{
					this.container.removeChildAt(i);
					length--;
				}				
			}
		}
	}
}